package com.changgou.seckill.service.impl;

import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.service.SecKillOrderService;
import com.changgou.utill.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;

public class SecKillOrderServiceImpl implements SecKillOrderService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    public static final String SECKILL_GOODS_KEY="seckill_goods_";

    public static final String SECKILL_GOODS_STOCK_COUNT_KEY="seckill_goods_stock_count_";

    @Override
    public boolean add(Long id, String time, String username) {
        //获取redis中的商品信息与库存信息,并进行判断
        //获取商品信息
        SeckillGoods seckillGoods= (SeckillGoods) redisTemplate.boundHashOps(SECKILL_GOODS_KEY+time).get(id);
        //获取库存
        String redisStock= (String) redisTemplate.boundValueOps(SECKILL_GOODS_STOCK_COUNT_KEY+id).get();
        if(StringUtils.isEmpty(redisStock)){
            return false;
        }
        int stock = Integer.parseInt(redisStock);
        if(seckillGoods==null||stock<=0){
            return false;
        }
        //执行redis的预扣减库存操作,并获取扣减之后的库存值
        //基于redis中的原子性操作:decrement(key,delta),increment(key,delta)
        Long decrement = redisTemplate.opsForValue().decrement(SECKILL_GOODS_STOCK_COUNT_KEY + id);

        //如果扣减之后的库存值<=0,则删除redis中响应的商品信息与库存信息
        if(decrement<=0){
            //扣减完库存以后,当前商品已经没有库存了
            //删除redis中的商品信息
            redisTemplate.boundHashOps(SECKILL_GOODS_KEY+time).delete(id);
            redisTemplate.delete(SECKILL_GOODS_STOCK_COUNT_KEY + id);
        }
        //基于mq完成mysql的数据同步,进行异步下单并扣减库存
        //消息体:秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setId(idWorker.nextId());
        seckillOrder.setSeckillId(id);
        seckillOrder.setMoney(seckillGoods.getCostPrice());
        seckillOrder.setUserId(username);
        seckillOrder.setSellerId(seckillGoods.getSellerId());
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setStatus("0");
        return true;
    }
}
